import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

// 定义 Store
export const useDeviceStore = defineStore(
  'device',
  () => {
    // 设备列表
    const deviceList = ref([])

    const deviceIdList = computed(() => {
      return deviceList.value.map((item) => item.deviceId)
    })
    /**
     * 添加设备
     * @param {Array<Object>} arr 要添加的设备列表
     * @param {String} arr[].deviceId 设备id
     * @param {String} arr[].name 设备名称
     * @param {String} arr[].rssi 设备信号强度
     * @param {String} arr[].advertisData 设备广播数据
     * @param {String} arr[].advertisServiceUUIDs 设备服务UUID
     */
    const addDevice = (arr) => {
      arr.forEach((item) => {
        deviceIdList.value.includes(item.deviceId) ||
          deviceList.value.push({ name: item.name, deviceId: item.deviceId })
      })
    }
    /**
     * 删除设备
     * @param {String} deviceId 设备ID
     */
    const deleteDevice = (deviceId) => {
      deviceList.value = deviceList.value.filter((item) => item.deviceId !== deviceId)
    }

    /**
     * 当前设备信息
     * {String} deviceId 设备id
     * {String} name 设备名称
     * {String} rssi 设备信号强度
     * {String} advertisData 设备广播数据
     * {String} advertisServiceUUIDs 设备服务UUID
     *
     * {Object} opts 设备服务特征值
     * {Object} criticalData 设备临界值
     */
    const curDevice = ref({})
    const setCurDevice = (obj) => {
      curDevice.value = obj
    }
    const setCurDeviceItem = (key, val) => {
      curDevice.value[key] = val
    }

    // 设备参数 读写特征值
    const getOpts = () => {
      return JSON.parse(JSON.stringify(curDevice.value.opts || {}))
    }

    const clear = () => {
      deviceList.value = []
      curDevice.value = {}
    }

    return {
      deviceList,
      addDevice,
      deleteDevice,
      curDevice,
      setCurDevice,
      setCurDeviceItem,
      getOpts,
      clear,
      // opts,
      // setOpts,
    }
  },
  {
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          return uni.setStorageSync(key, value)
        },
      },
    },
  },
)
